package org.jeecg.modules.hotel.leave.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.mapper.LwgyBaseBedMapper;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.mapper.LwgyBaseStudentMapper;
import org.jeecg.modules.hotel.arrangement.entity.LwgyHotelArrangement;
import org.jeecg.modules.hotel.arrangement.service.ILwgyHotelArrangementService;
import org.jeecg.modules.hotel.history.entity.LwgyHotelHistory;
import org.jeecg.modules.hotel.history.service.ILwgyHotelHistoryService;
import org.jeecg.modules.hotel.leave.entity.LwgyHotelLeaveSchool;
import org.jeecg.modules.hotel.leave.service.ILwgyHotelLeaveSchoolService;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 离校管理
 * @Author: jeecg-boot
 * @Date:   2023-02-14
 * @Version: V1.0
 */
@Api(tags="调退宿申请")
@RestController
@RequestMapping("/leave/lwgyHotelLeaveSchool")
@Slf4j
public class LwgyHotelLeaveSchoolController extends JeecgController<LwgyHotelLeaveSchool, ILwgyHotelLeaveSchoolService> {

    @Autowired
    private ILwgyHotelLeaveSchoolService lwgyHotelLeaveSchoolService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ILwgyHotelArrangementService lwgyHotelArrangementService;

    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;

    @Resource
    private LwgyBaseStudentMapper lwgyBaseStudentMapper;

    @Resource
    private LwgyBaseBedMapper lwgyBaseBedMapper;

    @Autowired
    private ILwgyHotelHistoryService lwgyHotelHistoryService;

    /**
     * 分页列表查询
     *
     * @param lwgyHotelLeaveSchool
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "离校管理-分页列表查询")
    @ApiOperation(value="离校管理-分页列表查询", notes="离校管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(LwgyHotelLeaveSchool lwgyHotelLeaveSchool,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<LwgyHotelLeaveSchool> queryWrapper = QueryGenerator.initQueryWrapper(lwgyHotelLeaveSchool, req.getParameterMap());
        Page<LwgyHotelLeaveSchool> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roles = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
        //管理员不限制
        //辅导员只看他自己学生申请
        //学生只看他提交的
        List<Map<String,String>> fdyList = null;
        if(roles.contains("fdy")){
            List<String> classId = lwgyBaseStudentService.getClassIdBySysUser(sysUser);
            if (oConvertUtils.listIsNotEmpty((classId))) {
                queryWrapper.in("student_class", classId);
            } else {
                queryWrapper.eq("student_class", "null");
            }
            /*		queryWrapper.in("admin_id",sysUser.getWorkNo());*/
        }else if(roles.contains("user_students")){
            queryWrapper.eq("student_number",sysUser.getWorkNo());
        }

        IPage<LwgyHotelLeaveSchool> pageList = lwgyHotelLeaveSchoolService.page(page, queryWrapper);

        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param lwgyHotelLeaveSchool
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "退宿办理-分页列表查询")
    @ApiOperation(value="退宿办理-分页列表查询", notes="退宿办理-分页列表查询")
    @GetMapping(value = "/queryCheckOutList")
    public Result<?> queryCheckOutList(LwgyHotelLeaveSchool lwgyHotelLeaveSchool,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<LwgyHotelLeaveSchool> queryWrapper = QueryGenerator.initQueryWrapper(lwgyHotelLeaveSchool, req.getParameterMap());
        Page<LwgyHotelLeaveSchool> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roles = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
        //管理员不限制
        //辅导员只看他自己学生申请
        //学生只看他提交的
        List<Map<String,String>> fdyList = null;
        if(roles.contains("fdy")){
            List<String> classId = lwgyBaseStudentService.getClassIdBySysUser(sysUser);
            if (oConvertUtils.listIsNotEmpty((classId))) {
                queryWrapper.in("student_class", classId);
            } else {
                queryWrapper.eq("student_class", "null");
            }
            /*		queryWrapper.in("admin_id",sysUser.getWorkNo());*/
        }else if(roles.contains("user_students")){
            queryWrapper.eq("student_number",sysUser.getWorkNo());
        }

        IPage<LwgyHotelLeaveSchool> pageList = lwgyHotelLeaveSchoolService.queryCheckOutList(page, queryWrapper);

        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param lwgyHotelLeaveSchool
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "确认离校-分页列表查询")
    @ApiOperation(value="确认离校-分页列表查询", notes="确认离校-分页列表查询")
    @GetMapping(value = "/queryConfirmList")
    public Result<?> queryConfirmList(LwgyHotelLeaveSchool lwgyHotelLeaveSchool,
                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                       HttpServletRequest req) {
        QueryWrapper<LwgyHotelLeaveSchool> queryWrapper = QueryGenerator.initQueryWrapper(lwgyHotelLeaveSchool, req.getParameterMap());
        Page<LwgyHotelLeaveSchool> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roles = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
        //管理员不限制
        //辅导员只看他自己学生申请
        //学生只看他提交的
        List<Map<String,String>> fdyList = null;
        if(roles.contains("fdy")){
            List<String> classId = lwgyBaseStudentService.getClassIdBySysUser(sysUser);
            if (oConvertUtils.listIsNotEmpty((classId))) {
                queryWrapper.in("student_class", classId);
            } else {
                queryWrapper.eq("student_class", "null");
            }
            /*		queryWrapper.in("admin_id",sysUser.getWorkNo());*/
        }else if(roles.contains("user_students")){
            queryWrapper.eq("student_number",sysUser.getWorkNo());
        }

        IPage<LwgyHotelLeaveSchool> pageList = lwgyHotelLeaveSchoolService.queryConfirmList(page, queryWrapper);

        return Result.OK(pageList);
    }

    /**
     * 离校管理-添加
     *
     * @param lwgyHotelLeaveSchool
     * @return
     */
    @AutoLog(value = "离校管理-添加")
    @ApiOperation(value = "离校管理-添加", notes = "离校管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody LwgyHotelLeaveSchool lwgyHotelLeaveSchool) {
        LwgyBaseStudent lwgyBaseStudent =lwgyBaseStudentMapper.getStudentByNumber(lwgyHotelLeaveSchool.getStudentNumber());
        if(oConvertUtils.isNotEmpty(lwgyBaseStudent)){
            lwgyHotelLeaveSchool.setStudentId(lwgyBaseStudent.getId());
            lwgyHotelLeaveSchool.setStudentSex(lwgyBaseStudent.getStudentSex());
            lwgyHotelLeaveSchool.setStudentCampus(lwgyBaseStudent.getStudentCampus());
            lwgyHotelLeaveSchool.setStudentCollege(lwgyBaseStudent.getStudentCollege());
            lwgyHotelLeaveSchool.setStudentMajor(lwgyBaseStudent.getStudentMajor());
            lwgyHotelLeaveSchool.setStudentYear(lwgyBaseStudent.getStudentYear());
            lwgyHotelLeaveSchool.setStudentClass(lwgyBaseStudent.getStudentClass());
        }
        LwgyBaseBed lwgyBaseBed = lwgyBaseBedMapper.getBedByStuId(lwgyBaseStudent.getId());
        if(oConvertUtils.isNotEmpty(lwgyBaseBed)){
            lwgyHotelLeaveSchool.setBuildingId(lwgyBaseBed.getBuildingId());
            lwgyHotelLeaveSchool.setUnitId(lwgyBaseBed.getUnitId());
            lwgyHotelLeaveSchool.setLayerId(lwgyBaseBed.getLayerId());
            lwgyHotelLeaveSchool.setRoomId(lwgyBaseBed.getRoomId());
        }
        lwgyHotelLeaveSchoolService.save(lwgyHotelLeaveSchool);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     *
     * @param lwgyHotelLeaveSchool
     * @return
     */
    @AutoLog(value = "离校管理-编辑")
    @ApiOperation(value="离校管理-编辑", notes="离校管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody LwgyHotelLeaveSchool lwgyHotelLeaveSchool) {
        lwgyHotelLeaveSchoolService.updateById(lwgyHotelLeaveSchool);
        return Result.OK("编辑成功!");
    }

    /**
     *  离校管理-编辑
     *
     * @param lwgyHotelLeaveSchool
     * @return
     */
    @AutoLog(value = "离校管理-编辑")
    @ApiOperation(value="离校管理-编辑", notes="离校管理-编辑")
    @PutMapping(value = "/updateState")
    public Result<?> updateState(@RequestBody LwgyHotelLeaveSchool lwgyHotelLeaveSchool) {
        lwgyHotelLeaveSchoolService.updateById(lwgyHotelLeaveSchool);
        lwgyHotelLeaveSchoolService.updateStateByNum(lwgyHotelLeaveSchool);
        return Result.OK("编辑成功!");
    }

    /**
     *  退宿管理-编辑
     *
     * @param lwgyHotelLeaveSchool
     * @return
     */
    @AutoLog(value = "退宿管理-编辑")
    @ApiOperation(value="退宿管理-编辑", notes="退宿管理-编辑")
    @PutMapping(value = "/updateHotelState")
    public Result<?> updateHotelState(@RequestBody LwgyHotelLeaveSchool lwgyHotelLeaveSchool) {
        lwgyHotelLeaveSchoolService.updateById(lwgyHotelLeaveSchool);
        String studentNumber = lwgyHotelLeaveSchool.getStudentNumber();
        //1. 退宿
        LwgyHotelArrangement lwgyHotelArrangement = lwgyHotelLeaveSchoolService.queryStudentId(studentNumber);
        lwgyHotelArrangementService.checkOutStu(lwgyHotelArrangement);
        //2. 存储到历史记录
        LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
        lwgyHotelHistory.setAfterBed(lwgyHotelArrangement.getAfterBed());
        lwgyHotelHistory.setBehavior("leave_bed");
        lwgyHotelHistory.setPersonId(lwgyHotelArrangement.getStudentId());
        lwgyHotelHistory.setSort("");
        lwgyHotelHistory.setBeforeBed(lwgyHotelArrangement.getId());
        lwgyHotelHistory.setCreateTime(lwgyHotelLeaveSchool.getUpdateTime());
        lwgyHotelHistoryService.save(lwgyHotelHistory);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "离校管理-通过id删除")
    @ApiOperation(value = "离校管理-通过id删除", notes = "离校管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        lwgyHotelLeaveSchoolService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "离校管理-批量删除")
    @ApiOperation(value = "离校管理-批量删除", notes = "离校管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.lwgyHotelLeaveSchoolService.removeByIds(Arrays.asList(ids.split(",")));
        System.out.println();
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "行为管理-通过id查询")
    @ApiOperation(value="行为管理-通过id查询", notes="行为管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
        LwgyHotelLeaveSchool lwgyHotelLeaveSchool = lwgyHotelLeaveSchoolService.getById(id);
        if(lwgyHotelLeaveSchool == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(lwgyHotelLeaveSchool);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param lwgyHotelLeaveSchool
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LwgyHotelLeaveSchool lwgyHotelLeaveSchool) {
        return super.exportXls(request, lwgyHotelLeaveSchool, LwgyHotelLeaveSchool.class, "行为管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LwgyHotelLeaveSchool.class);
    }

    /**
     *  批量确认缴费
     *
     * @param
     * @return
     */
    @AutoLog(value = "批量确认缴费")
    @ApiOperation(value="批量确认缴费", notes="批量确认缴费")
    @PutMapping(value = "/batchArrears")
    public Result<?> batchArrears(@RequestBody List<LwgyHotelLeaveSchool> lwgyHotelLeaveSchool) {
        lwgyHotelLeaveSchoolService.updateBatchById(lwgyHotelLeaveSchool);
        return Result.OK("批量确认成功!");
    }

    /**
     *  批量确认归还图书
     *
     * @param
     * @return
     */
    @AutoLog(value = "批量确认归还图书")
    @ApiOperation(value="批量确认归还图书", notes="批量确认归还图书")
    @PutMapping(value = "/batchBooks")
    public Result<?> batchBooks(@RequestBody List<LwgyHotelLeaveSchool> lwgyHotelLeaveSchool) {
        lwgyHotelLeaveSchoolService.updateBatchById(lwgyHotelLeaveSchool);
        return Result.OK("批量确认成功!");
    }

    /**
     * 批量离校
     *
     * @param stuIds
     */
    @AutoLog(value = "批量离校")
    @ApiOperation(value = "批量离校", notes = "批量离校")
    @PostMapping(value = "/confirmLeave")
    public Result<?> confirmLeave(@RequestBody String stuIds) {
        if (oConvertUtils.isNotEmpty(stuIds)) {
            if (stuIds.length() > 11) {
                stuIds = stuIds.substring(11, stuIds.length() - 2);
                System.out.println(stuIds);
                // 批量离校
                lwgyHotelArrangementService.leaveSchool(stuIds);
                return Result.OK("编辑成功!");
            }
        }
        return Result.error("编辑失败!");
    }

    /**
     * 批量离校
     *
     * @param lwgyHotelLeaveSchool
     */
    @AutoLog(value = "批量离校")
    @ApiOperation(value = "批量离校", notes = "批量离校")
    @PutMapping(value = "/batchLeave")
    public Result<?> batchLeave(@RequestBody List<Map<String, String>> lwgyHotelLeaveSchool) {
        String ids = "";
        List<LwgyHotelLeaveSchool> leaveList = new ArrayList<>();
        for (Map<String, String> map : lwgyHotelLeaveSchool) {
            ids += map.get("id") + ",";
        }
        //批量修改leave_school表中的离校学生的状态
        lwgyHotelLeaveSchoolService.updateStuState(ids);
        //批量清空原来的住宿信息
        //lwgyHotelArrangementService.cleanBed(ids);
        //for (LwgyHotelLeaveSchool l:lwgyHotelLeaveSchool) {
        //    studentId += lwgyHotelLeaveSchool.get("student_id") + "";
        //}
        //lwgyHotelArrangementService.leaveSchool(studentId);
        return Result.error("批量确认成功!");
    }
}
